<template>
  <div
    :style="{ paddingTop: `${searchBarTop}px` }"
    class="healthDetail relative px-34rpx pb-150rpx">
    <image
      :src="`${cdnUrl}/imgs/noOpen/bg.png${imgVersion}`"
      mode="scaleToFill"
      class="pointer-events-none fixed bottom-0 left-0 right-0 top-0 z--9 h-100% w-100%"
    />
    <div @click="goHealthBack">
      <div class="z-999 mb-16rpx flex items-center">
        <uni-icons type="back" size="28" />
      </div>
    </div>
    <div class="mb-62rpx mt-46rpx w-100% flex items-center">
      <div class="mr-16rpx w-100rpx text-24rpx text-hex-7C8699">测评进度</div>
      <div class="mr-16rpx h-32rpx w-70% rounded-46rpx bg-[rgb(232,242,199)]">
        <div class="progress relative h-32rpx rounded-46rpx"
             :style="{ width: `${questionPercent}%`, transition: 'width 1s ease' }">
          <div class="masker absolute rounded-46rpx" />
          <image
            :src="`${cdnUrl}/imgs/healthDetail/progress.png${imgVersion}`"
            mode="scaleToFill"
            class="absolute bottom-32rpx h-50rpx w-56rpx -right-15rpx"
          />
        </div>
      </div>
      <div class="w-80rpx">
        <text class="text-hex-abcd03">{{ spliceIndex+1 }}</text>
        <text class="text-hex-999">/{{ cloneQuestionList.length }}</text>
      </div>
    </div>
    <div
      v-if="upQuestionShow || downQuestionShow"
      class="fixed bottom-0 left-0 right-0 rounded-t-36rpx bg-hex-ffffff py-32rpx">
      <div class="flex items-center justify-around text-28rpx font-bold text-hex-29B897">
        <div
          v-if="upQuestionShow"
          class="btn-normal-bg h-76rpx w-230rpx flex items-center justify-center rounded-56rpx"
          :class="{ activeWidth: !downQuestionShow }"
          @click="getUpQuestion"
        >上一页</div>
        <div
          v-if="downQuestionShow"
          class="btn-normal-bg h-76rpx w-230rpx flex items-center justify-center rounded-56rpx"
          :class="{ activeWidth: !upQuestionShow }"
          @click="getDownQuestion"
        >{{ nextStep }}</div>
      </div>
    </div>
    <div v-if="questionitem" class="mb-48rpx">
      <div
        v-for="cItem in questionitem"
        class="mb-48rpx"
      >
        <div
          v-if="cItem.content"
          class="mb-48rpx min-h-50rpx w-100% text-36rpx font-600">{{ cItem.sortId }}, {{ cItem.content }}</div>
        <div class="box-border h-88rpx flex items-center justify-around rounded-74rpx bg-hex-ffffff">
          <div
            v-for="item in cItem.options"
            class="box-border h-100% flex items-center text-28rpx text-hex-7C8699"
            :class="{ activecolor: item.isSelected }"
            @click="answerItem(item, cItem)"
          >
            <div class="flex items-center">
              <text
                class="mr-10rpx"
                :class="{ active: item.isSelected }"
              >{{ item.name }}</text>
              {{ item.content }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>

let questionType: any = $ref('')
let recordId: any = $ref('')
let sex: any = $ref()
let questionList: any = $ref([])
let searchBarTop: any = $ref('24')
let questionitem: any = $ref()//当前页面展示的题目
let spliceIndex: any = $ref(0)//展示数组第几个
let upQuestionShow: any = $ref(false)//是否展示上一题按钮
let downQuestionShow: any = $ref(true)//是否展示展示下一题按钮
let currentQuestion: any = $ref('0')//当前的题目
let currentIndex: any = $ref('')
onLoad((options) => {
  if (options) {
    questionType = options.questionType
    recordId = options.evaluationId
    sex = options.sex
    currentIndex = options.spliceIndex
  }
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
let cloneQuestionList: any = $ref([])
const getQuestionList = async () => {
  const reqData = {
    method: 'get',
    data: {
      questionCategoryId: questionType,
      evaluationId: recordId,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/health/questions/wholeQuestionnaire', reqData)
  if (status === 200) {
    questionList = data.result.questions
    let sexList: any = []
    //按照性别分组
    if (sex === '1') {
      sexList = questionList.filter(item => item.sex !== 0)
    } else {
      sexList = questionList.filter(item => item.sex !== 1)
    }
    let tempIndex = sexList.findIndex((item) => item.id === currentIndex)
    spliceIndex = Math.floor(Number(tempIndex + 1) / 10)
    //添加题序,并且记录答题
    sexList.forEach((item, index) => {
      item.sortId = index + 1
      item.options.forEach(option => {
        if (option.selected === true) {
          option.isSelected = 1
        } else {
          option.isSelected = 0
        }
      })
    })
    cloneQuestionList = arrayGroup(sexList, 10)
    if (Number(spliceIndex) > 0) {
      upQuestionShow = true
    }
    if (Number(spliceIndex) + 1 >= cloneQuestionList.length) {
      upQuestionShow = true
      nextStep = '提交'
    } else {
      nextStep = '下一页'
    }
    // console.log(spliceIndex)
    questionitem = cloneQuestionList[spliceIndex]
    // console.log(questionitem)
  }
}
const arrayGroup = (array, groupNum: number) => {
  let index = 0
  let newArray: any = []
  while (index < array.length) {
    newArray.push(array.slice(index, index += groupNum))
  }
  return newArray
}
// 更新测评记录
const upDateEvaluation = async (questionId, optionId) => {
  const reqData = {
    method: 'put',
    data: {
      id: Number(recordId),
      question_id: Number(questionId), //问题编码
      question_option_id: Number(optionId), //问题选项编码
    },
  }
  const { data, status, error } = await Fetch('/api/s/health/evaluations', reqData)
}
//体质问题回调
const answerItem = async (item, cItem) => {
  const reqData = {
    method: 'post',
    data: {
      question_category_id: questionType, //问题类型编码
      evaluation_id: recordId, //测评记录编码
      question_id: item.questionId, //问题编码
      questionnaire_id: null, //问卷编码
      question_option_id: item.id, //问题选项编码
      sex: cItem?.sex, //性别
      group_tag: cItem?.groupTag, //体质问题分组
    },
  }
  const { data, status, error } = await Fetch('/api/s/health/evaluationFlows', reqData)
  if (status !== 200 || data.code !== 0) {
    // console.log('答题错误')
  }
  for (let index = 0; index < questionitem.length; index++) {
    const element = questionitem[index]
    if (element.id === item.questionId) {
      element.options.forEach((optionItem) => {
        if (optionItem.id === item.id) {
          optionItem.isSelected = 1
        } else {
          optionItem.isSelected = 0
        }
      })
    }
  }
  // questionitem.forEach((nowItem) => {
  //   if (nowItem.id === item.questionId) {
  //     nowItem.options.forEach((optionItem) => {
  //       if (optionItem.id === item.id) {
  //         optionItem.isSelected = 1
  //       } else {
  //         optionItem.isSelected = 0
  //       }
  //     })
  //   }
  // })
  upDateEvaluation(item.questionId, item.id)
}
let nextStep: any = $ref('下一页')

const getQuestionItem = () => {
  if (spliceIndex >= 1) {
    upQuestionShow = true
  }
  // 如果相等点击的选项等于长度就跳转到报告页面
  if (spliceIndex === cloneQuestionList.length) {
    setTimeout(() => {
      navTo(`/pages-health/healthPhiReport?evaluationId=${recordId}&type=${questionType}`)
    }, 600)
    return
  }
  setTimeout(() => {
    questionitem = cloneQuestionList[spliceIndex]
  }, 100)
}
const questionPercent = $computed(() => {
  return (spliceIndex + 1) * 100 / cloneQuestionList.length
})

// 上一页
const getUpQuestion = useThrottleFn(() => {
  spliceIndex--
  nextStep = '下一页'
  if (spliceIndex === 0) {
    upQuestionShow = false
  }
  getQuestionItem()
}, 100)
//下一页
const getDownQuestion = useThrottleFn(() => {
  let recordItem: any = []
  questionitem.forEach((nowItem, index) => {
    let isDown = nowItem.options.some(item => item.isSelected === 1)
    recordItem.push(isDown)
  })
  if (recordItem.includes(false)) {
    uni.showToast({
      title: '亲，有未答完的题目,请继续答题',
      icon: 'none',
      duration: 1800,
    })
    return
  }
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  })
  if (spliceIndex + 2 >= cloneQuestionList.length) {
    upQuestionShow = true
    nextStep = '提交'
  } else {
    nextStep = '下一页'
  }
  if (!(Number(spliceIndex) === Number(cloneQuestionList.length))) {
    spliceIndex++
  }
  getQuestionItem()
}, 100)

onMounted(() => {
  getQuestionList()
})

</script>

<style lang="scss" scoped>

.healthDetail{
  .active{
    width: 46rpx;
    height: 46rpx;
    background: linear-gradient(176deg, #ABCD05 0%, #5CDF79 100%);;
    box-shadow: 0rpx 4rpx 8rpx 0rpx #abcd03;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }

  .font-alimamaShuHeiTi{
    font-family:alimamaShuHeiTi;
  }

  @keyframes wrapper-gradient {
    // 0% {
    //   transform: translateY(100%);
    // }

    // 100% {
    //   transform: translateY(0);
    // }
    0% {
      transform:translate(-100px);
      opacity:0;
    }

    50% {
      transform:translate(-20px);
      opacity:.5;
    }

    100% {
      transform:translate(0);
      opacity:1;
    }
  }

  .activeclass {
    overflow: hidden;
    animation: wrapper-gradient .1s linear;
    transform:translate(0);
    transition-delay: .1s;
  }

  .progress {
    background: linear-gradient(-45deg, #45E9C3 36%, #ABCD03 28%, #ABCD03 67%, #45E9C3 25%);
    background-size: 18px 16px;
    animation: load 1s;

    .masker {
      inset: 0;
      opacity: .8;

      // background: linear-gradient(90deg, #1c7bda 20%, #fff 100%)
      background-color: #abcd03;
    }

  }

  @keyframes load {
    0% {
      width: 0;
    }
  }

  .activeWidth{
    width: 492rpx;
  }

  .activecolor{
    color: #222;
  }
}
</style>
